package com.foosun.sweb.util
{
	import com.adobe.serialization.json.JSON;
	
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;



	public class HttpUtil
	{
		
		
		
		private var httpService:HTTPService = new HTTPService();
		private var url:String;
		private var params:Object;
		private var resultFormat:String;
		private var _successhandler:Function;
		private var _faulthandler:Function;
		

		
		public function HttpUtil(_url:String,_params:Object = null,_successhandler:Function = null,_faulthandler:Function = null,_resultFormat:String = "object")
		{
			this.url = NetUrls.SERVER + _url;
			this.params = _params;
			this.resultFormat = _resultFormat;
			this._successhandler = _successhandler;
			this._faulthandler = _faulthandler;
			
			httpService.url = this.url;
			httpService.showBusyCursor = true;
			httpService.resultFormat = this.resultFormat;
			httpService.useProxy = false;

			httpService.addEventListener(ResultEvent.RESULT,successhandler);
			httpService.addEventListener(FaultEvent.FAULT,faulthandler);
		}



		public static function post(_url:String,_params:Object = null,_successhandler:Function = null,_faulthandler:Function = null,_resultFormat:String = "object"):void {
            var service:HttpUtil = new HttpUtil(_url,_params,_successhandler,_faulthandler,_resultFormat);
            service.post();
		}

		public static function get(_url:String,_params:Object = null,_successhandler:Function = null,_faulthandler:Function = null,_resultFormat:String = "object"):void {
            var service:HttpUtil = new HttpUtil(_url,_params,_successhandler,_faulthandler,_resultFormat);
            service.get();
		}

        public function post():void {
            httpService.method = "POST";
            httpService.send(this.params);
        }

		public function get():void {
			httpService.method = "GET";
			httpService.send(this.params);
		}
		
		private function successhandler(event:ResultEvent):void{
			var result:String = event.message.body.toString();
			trace(result);
			if(this._successhandler != null) {
				var data:Object = event.result;
				data = JSON.decode(data.toString());
				this._successhandler(event,data);
			}
			this.httpService.disconnect();
		}
		private function faulthandler(event:FaultEvent):void{
			var result:String = event.message.toString();
			trace(result);
			if(this._faulthandler != null) {
				this._faulthandler(event);
			}
			this.httpService..disconnect();
		}
	}
}